import {DeleteOutlined, EditOutlined, PlusOutlined, SearchOutlined, SyncOutlined} from '@ant-design/icons'
import {useRequest} from '@umijs/hooks'
import {Button, Card, Form, Input, message, Popconfirm, Select, Table, Tag} from 'antd'
import {Store} from 'rc-field-form/lib/interface'
import React, {useEffect, useState} from 'react'
import {useDispatch, useSelector} from 'react-redux'
import TableToolbar from '../../../components/TableSetting/TableToolbar'
import {fetchRequest} from '../../../utils/Request'
import {url} from '../../../utils/url'
import {actionTypes} from '../actionTypes'
import AddDepartment from './AddDepartment'
import ModifyDepartment from './ModifyDepartment'
import './style.css'

interface AddVisible {
    visible: boolean,
    deptID: null | undefined | string
}

export default function DepartmentTable() {

    const [addVisible, setaddVisible] = useState<AddVisible>({visible: false, deptID: null})
    const [modifyVisible, setmodifyVisible] = useState({visible: false, content: null})

    const [columnsKey, setcolumnsKey] = useState<any[]>([])

    const [realColumns, setrealColumns] = useState<any[]>([])

    const dispatch = useDispatch()


    const columns = [
        {title: "组织名称", dataIndex: 'title', key: 'title'},
        {title: "排序", dataIndex: 'order', key: 'order'},
        {title: "创建时间", dataIndex: 'createDate', key: 'createDate'},
        {
            title: "操作", key: "operation", render: (record: any) => {
                if (record.canEdit)
                    return <small onClick={e => e.stopPropagation()}>
                        <Tag className="tags-hover"
                             color="#108ee9"
                             onClick={() => setmodifyVisible({visible: true, content: record})}
                             icon={<EditOutlined/>}>编辑</Tag>
                        <Tag style={record.level === 3 ? {display: 'none'} : undefined}
                             className="tags-hover"
                             color="#23c6c8"
                             onClick={() => setaddVisible({visible: true, deptID: record.key})}
                             icon={<PlusOutlined/>}>新增</Tag>
                        <Popconfirm title="确定要删除？"
                                    onConfirm={(e: any) => onDelete({deptID: record.deptID})}>
                            <Tag className="tags-hover delete"
                                 color="#f50"
                                 icon={<DeleteOutlined/>}>删除</Tag>
                        </Popconfirm>
                    </small>
                else
                    return <small></small>
            }
        }]


    async function onDelete(params: any) {
        try {
            const json = await fetchRequest(url.DELETE_DEPART_URL, params);
            if (json.success) {
                getDept.run()
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)

        }
    }

    //获取redux中的数据
    const data = useSelector((state: StoreState) => {
        return state.deptManage
    })


    function onColumnsChange(checkedList: any[]) {
        // console.log(checkedList)
        setcolumnsKey(checkedList)
    }


    //新增取消的时候
    function onAddCancel() {
        setaddVisible({visible: false, deptID: null})
    }

    const [form] = Form.useForm()


    //点击搜索按钮
    function handleFinish(values: Store) {
        // console.log(values)
        //TODO 后续请求数据
    }

    //点击重置按钮
    function handleReset() {
        // console.log(values)
        form.resetFields();
        //TODO 后续请求数据
    }

    //查询框
    const searchForm = (
        <Card className="search-form"> <Form form={form} layout="inline" initialValues={{deptState: "1"}}
                                             onFinish={handleFinish} onReset={handleReset}>

            <Form.Item className="form-control-item" name="deptName" label="组织名称">
                <Input className="search-form-item"/>
            </Form.Item>

            <Form.Item className="form-control-item" name="deptState" label="组织状态">
                <Select className="search-form-item">
                    <Select.Option value={"1"}>所有</Select.Option>
                    <Select.Option value={"2"}>正常</Select.Option>
                    <Select.Option value={"3"}>停用</Select.Option>
                </Select>
            </Form.Item>


            <Form.Item className="form-control-item">
                <Button key="1" type="primary" icon={<SearchOutlined/>} htmlType="submit"
                        style={{marginRight: '8px'}}>搜索</Button>
                <Button key="2" icon={<SyncOutlined/>} htmlType="reset">重置</Button>

            </Form.Item>

        </Form>
        </Card>)


    function onModifyCancel() {
        setmodifyVisible({visible: false, content: null})
    }

    //监听变化
    useEffect(() => {
        const realColumns = columns.filter(item => columnsKey.indexOf(item.key) !== -1)
        setrealColumns(realColumns)
    }, [columnsKey])

    const getDept = useRequest(getDeptInfo, {
        loadingDelay: 200
    })


    //网络请求
    async function getDeptInfo() {
        try {
            const json = await fetchRequest(url.GET_ALL_DEPT, "");
            console.log(json)
            if (json.success) {
                //删除空的子节点
                deleteEmpty(json.deptData)
                dispatch({type: actionTypes.GET_DEPT_TABLE, payload: json.deptData})
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }


    //递归删除空的children
    function deleteEmpty(arr: any[]) {
        arr.map(item => {
            if (item.children.length === 0) {
                delete item.children
            } else {
                deleteEmpty(item.children)
            }
        })
    }


    //点击刷新按钮
    function onRefresh() {
        getDept.run()
    }

    //点击新增按钮
    function onAdd() {
        setaddVisible({visible: true, deptID: undefined})
    }

    return (
        <div>
            <Card className="search-form-table">
                <TableToolbar tableName="组织管理表"
                              columns={columns}
                              onColumnsChange={onColumnsChange}
                              onRefresh={onRefresh}
                              onAdd={onAdd}/>
                <Table loading={getDept.loading}
                       columns={realColumns}
                       dataSource={data.deptData}
                       expandable={{expandRowByClick: true}}
                       pagination={false}/>
                       {
                           addVisible.visible ?
                               <AddDepartment onAddSuccess={onRefresh}
                                              visible={addVisible.visible}
                                              onAddCancel={onAddCancel}
                                              deptID={addVisible.deptID}/>
                                              : null
                       }
                       {
                           modifyVisible.visible ?
                               <ModifyDepartment onAddSuccess={onRefresh}
                                                 visible={modifyVisible.visible}
                                                 onAddCancel={onModifyCancel}
                                                 content={modifyVisible.content}/>
                                                 : null
                       }
            </Card>
        </div>
    )
}
